package com.engc.common.utils;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.ResourceBundle;
import java.util.zip.GZIPInputStream;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.engc.common.bean.SysUserInfo;
import com.engc.common.fileupload.UploadJson;
import com.engc.common.service.BaseService;

/**
 * 文件管理
 * @author xf
 *
 */
@Controller
@RequestMapping("file")
public class FileController {
	private static ResourceBundle bundle = ResourceBundle.getBundle("config/fileserver");
	private static final String SERVER_IP = bundle.getString("ServerIp");
	private static final String SERVER_PORT = bundle.getString("ServerPort");
	
	@Resource
	private BaseService baseService;
	
	@RequestMapping("/view")
	public String view(HttpServletRequest request) {
		String file_url="http://"+SERVER_IP+":"+SERVER_PORT;
		request.setAttribute("file_url", file_url);
		return "base/file/file";
	}
	
	/**
	 * 新增文件
	 * @param request
	 * @return
	 */
	@RequestMapping("/save")
	@ResponseBody
	public String save(HttpServletRequest request) {
		Map<String, Object> record =BaseUtils.getInsertParam(request);
		UploadJson up=new UploadJson();
		try{
		     record = up.getUploadFile(request,record,"fileurl");
		     System.out.println(record);
		     record.put("id", baseService.getSeqValue("S_BASE_FILE"));
		     record.put("status", "");
			 record.put("name", record.get("filename"));
			 record.remove("filename");
			 record.remove("callback");
		     System.out.println(record);

			/*// 信息推送
			PushManager manager = PushManager.getInstance();
			// 推送给系统管理员，通知审核
			ArrayList<String> useridList = BaseUtils.getAdminIds();
			// 活动当前申请的用户ID和名称
			SysUserInfo user = BaseUtils.getCurrentUser(request);
			if (user == null) {
				return "操作失败,用户登录已注销，请重新登录";
			}
			String username = user.getUsername();
			String msgInfo = "尊敬的【系统管理员】,用户【" + username + "】上传了文件【"+record.get("name")+"】,请审核!";
			manager.pushNew(user.getUserid(), msgInfo, record.get("id").toString(), useridList,ReviewCode.FILE_UPLOAD_REVIEWING);
		     
		     baseService.Insert("BASE_FILE", record);*/
			return "增加成功";
		}catch (Exception e) {
			return "增加失败,请联系管理员";
		}
		
	}
	
	
	
	/**
	 * 修改文件
	 * @param request
	 * @return
	 */
	@RequestMapping("/update")
	@ResponseBody
	public String Update(HttpServletRequest request) {
		Map<String,Object> record = BaseUtils.getUpdateParam(request, "id");
		System.out.println(record);
		UploadJson up=new UploadJson();
		try {
			  // record = up.getUploadFile(request,record,"fileurl",BaseCommonality.FILE_TYPE);
			 System.out.println("-----2----"+record);
			 record.put("name", record.get("filename"));
			 record.remove("filename");
			 record.put("fileurl", record.get("filetext"));
			 record.remove("filetext");
			baseService.Update("BASE_FILE", record, "id=?", request.getParameter("id"));
			return "修改成功";
		} catch (Exception e) {
			e.printStackTrace();
			return "修改失败，请联系管理员";
		}
	}
	/**
	 * 删除文件
	 * @param request
	 * @return
	 */
	@RequestMapping("/delete")
	@ResponseBody
	public Map<String, Object> Delete(HttpServletRequest request) {
		String id = request.getParameter("id");
		try {
			baseService.Delete("BASE_FILE", "id=?", id);
			return BaseUtils.getSuccessMessage("删除成功");
		} catch (Exception e) {
			e.printStackTrace();
			return BaseUtils.getErrorMessage("删除失败");
		}
	}
	
	/**
	 * 审核文件
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/apply")
	@ResponseBody
	public Map<String,Object> Apply(HttpServletRequest request) throws Exception{
		Map<String,Object> getapplyData = BaseUtils.getUpdateParam(request, "id");
		String id = request.getParameter("id");
		try {
			baseService.Update("BASE_FILE", getapplyData, "id=?", id);		
			return  BaseUtils.getSuccessMessage("审核成功");
		} catch (Exception e) {
			e.printStackTrace();
			return BaseUtils.getErrorMessage("审核失败，系统发生故障，请联系管理员");
			
		}
	}

    @RequestMapping("/fileList")
    public String fileList(HttpServletRequest request){
        Map<String, Object> record = BaseUtils.getInsertParam(request);
        Object fileId = record.get("fileId");
        Object type = record.get("type");
        if (!BaseUtils.isEquals(type, "1") && !BaseUtils.isEquals(type, "2") &&
                !BaseUtils.isEquals(type, "3") && !BaseUtils.isEquals(type, "4")){
            type = null;
        }
        if (fileId != null){
            Map<String, Object> fileInfo = baseService.Read("select id, name,type, fileurl,time  from base_file t where t.status=1 and t.id=? ", fileId);
            if (!fileInfo.isEmpty()){
                fileInfo.put("fileurl", BaseUtils.completePicUrl(fileInfo.get("fileurl")));
                List<Map<String, Object>> result = new ArrayList<Map<String, Object>>();
                result.add(fileInfo);
                request.setAttribute("total", 1);
                request.setAttribute("list", result);
                return "front/file/filelist";
            }
        }
        Integer page;
        try {
            page = Integer.parseInt(record.get("page").toString());
        }catch (Exception e){
            page = 0;
        }
        String sql = "select id, name,type, fileurl,time  from base_file t where t.status=1 ";
        if (type != null){
            sql += "and t.type=? ";
        }
        sql += "order by t.time desc ";
        if (type == null){
            request.setAttribute("total", baseService.getTotal(sql) );
        }else {
            request.setAttribute("total", baseService.getTotal(sql, type) );
        }

        request.setAttribute("page", page);
        request.setAttribute("type", type);
        List<Map<String, Object>> list;
        if (type == null){
            list = baseService.Query_SliceOracle(sql, page+1, 20 );
        }else {
            list = baseService.Query_SliceOracle(sql, page+1, 20, type);
        }

        for (Map<String, Object> temp : list){
            temp.put("fileurl", BaseUtils.completePicUrl(temp.get("fileurl")));
        }
        request.setAttribute("list", list);
        return "front/file/filelist";
    }
	
	
	 /**
	 *下载文件
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/loadfile")
	public void loadfile(HttpServletRequest request,HttpServletResponse response)throws IOException{
		String fileurl=request.getParameter("fileurl");
		String fileName=fileurl.substring(fileurl.lastIndexOf("/")+1, fileurl.length());
		 URL url = new URL(fileurl);
		 URLConnection conn = url.openConnection();
		 InputStream is = conn.getInputStream();
		  String code=conn.getHeaderField("Content-Encoding");
		  if ((null!=code)&& code.equals("gzip"))
		  {
		   GZIPInputStream gis = new GZIPInputStream(is);
		  
		   // 1K的数据缓冲
		   byte[] bs = new byte[1024];
		   // 读取到的数据长度
		   int len;
		   // 输出的文件流
		   response.setHeader("Content-Disposition", "attachment;fileName="+ fileName);
		   OutputStream os =response.getOutputStream();
		   // 开始读取
		   while ((len = gis.read(bs)) != -1) {
		    os.write(bs, 0, len);
		   }
		   // 完毕，关闭所有链接
		   gis.close();
		   os.close();
		   is.close();
		  
		  }
		  else
		  {
		  
		   // 1K的数据缓冲
		   byte[] bs = new byte[1024];
		   // 读取到的数据长度
		   int len;
		   // 输出的文件流
		   response.setHeader("Content-Disposition", "attachment;fileName="+ fileName);
		   OutputStream os =response.getOutputStream();
		   // 开始读取
		   while ((len = is.read(bs)) != -1) {
		    os.write(bs, 0, len);
		   }
		   // 完毕，关闭所有链接
		   os.close();
		   is.close();
		  }

	}
}
